package com.warren.scheduler.controller;

import com.warren.annotation.ControllerEndpoint;
import com.warren.response.Result;
import com.warren.scheduler.entity.QuartzBean;
import com.warren.scheduler.utils.QuartzUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author warren
 * @create 2021-05-11 16:23
 * @Description
 */
@RestController
@RequestMapping("/quartz")
@Api(value = "定时任务",tags = "定时任务接口")
public class QuartzController {
    //注入任务调度
    @Resource
    private Scheduler scheduler;

    @ControllerEndpoint(exceptionMessage = "创建失败",operation = "创建定时任务")
    @ApiOperation(value = "创建定时任务")
    @PostMapping("/create")
    public Result createJob(@RequestBody QuartzBean quartzBean) throws SchedulerException, ClassNotFoundException{

        QuartzUtils.createScheduleJob(scheduler,quartzBean);
        return Result.ok().message("已创建任务");
    }

    @ControllerEndpoint(exceptionMessage = "暂停任务失败",operation = "暂停定时任务")
    @ApiOperation(value = "暂停定时任务")
    @PostMapping("/pause")
    public Result pauseJob(String jobName) throws SchedulerException{
        QuartzUtils.pauseScheduleJob(scheduler,jobName);
        return Result.ok().message("已暂停成功");
    }

    @ControllerEndpoint(exceptionMessage = "运行任务失败",operation = "运行暂停定时任务")
    @ApiOperation(value = "运行定时任务")
    @PostMapping("/run")
    public Result runOnce(String jobName)throws SchedulerException{
        QuartzUtils.runOnce(scheduler,jobName);
        return Result.ok().message( "运行任务" + jobName + "成功");
    }

    @ControllerEndpoint(exceptionMessage = "恢复任务失败",operation = "恢复定时任务")
    @ApiOperation(value = "恢复定时任务")
    @PostMapping("/resume")
    public Result resume(String jobName) throws SchedulerException {
        QuartzUtils.resumeScheduleJob(scheduler,jobName);
        return Result.ok().message("恢复定时任务成功：" + jobName);
    }

    @ControllerEndpoint(exceptionMessage = "更新任务失败",operation = "更新定时任务")
    @ApiOperation(value = "更新定时任务")
    @PostMapping("/update")
    public Result update(@RequestBody QuartzBean quartzBean)throws SchedulerException{
        QuartzUtils.updateScheduleJob(scheduler,quartzBean);
        return Result.ok().message("更新定时任务调度信息成功");
    }

    @ControllerEndpoint(exceptionMessage = "删除任务失败",operation = "删除定时任务")
    @ApiOperation(value = "删除定时任务")
    @PostMapping("/delete")
    public Result delete(String jobName) throws SchedulerException {
        QuartzUtils.deleteScheduleJob(scheduler,jobName);
        return Result.ok().message("删除定时任务成功");
    }
}
